package com.wtwd.wtwddevice.listener.deviceServerMsg.handler.impl;

import com.wtwd.device.annotation.MsgType;
import com.wtwd.device.constant.*;
import com.wtwd.device.model.HeartRate;
import com.wtwd.device.mqtentity.MessageBase;
import com.wtwd.device.protocol.AppProtocol;
import com.wtwd.device.protocol.WTProtocol;
import com.wtwd.device.util.DateUtils;
import com.wtwd.wtwddevice.listener.deviceServerMsg.handler.IMsgHandler;
import com.wtwd.wtwddevice.model.entity.DeviceHeartRate;
import com.wtwd.wtwddevice.service.IAppCommService;
import com.wtwd.wtwddevice.service.IDeviceHeartRateService;
import com.wtwd.wtwddevice.service.IDeviceService;
import com.wtwd.wtwddevice.service.IFrequencyService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 设备回复
 * 平常心率数据
 */
@MsgType(MsgTypeEnum.W_HRTSTART)
@Component
public class SetHrThresholdHandlerImpl implements IMsgHandler {


    @Resource
    private IDeviceHeartRateService deviceHeartRateService;

    @Resource
    private IDeviceService deviceService;


    @Resource
    private IAppCommService appCommService;


    @Resource
    private IFrequencyService frequencyService;


    @Override
    public void handleMsg(MessageBase messageBase) {
        WTProtocol wtProtocol = messageBase.getWtProtocol();
        String body = wtProtocol.getBody();
        String[] dataArray = body.split(SeparatorConstant.POUND_SIGN);
        Integer heartRate = Integer.valueOf(dataArray[0]);
        if (heartRate.equals(0)) return;
        Integer isWear = Integer.valueOf(dataArray[1]);
        Long deviceId = deviceService.getDeviceIdByImei(wtProtocol.getImei());
        DeviceHeartRate heartRateData = new DeviceHeartRate();
        heartRateData.setDeviceId(deviceId);
        heartRateData.setHeartRate(heartRate);
        heartRateData.setTime(wtProtocol.getTime());
        heartRateData.setNumber(wtProtocol.getNumber());
        heartRateData.setType(messageBase.getType());
        heartRateData.setIsWear(isWear);
        heartRateData.setCreateTime(new Date().getTime());
        heartRateData.setUpdateTime(new Date().getTime());
        deviceHeartRateService.insert(heartRateData);
        frequencyService.updateState(deviceId, FrequencyTypeEnum.HEARTRATE.getType(), CmdStateEnum.SUCCESS.getState());
        //推送到app
        HeartRate data = new HeartRate();
        BeanUtils.copyProperties(heartRateData, data);
        AppProtocol appProtocol = AppProtocol.builder()
                .imei(wtProtocol.getImei())
                .cmdName(MsgTypeEnum.APP_SET_W_HRTSTART.getCmdName())
                .data(data)
                .build();
        appCommService.pushDeviceState(deviceId, appProtocol);
    }
}
